<?php
declare (strict_types=1);

namespace app\admin\service\iot;

use aliyun\AliyunOss;
use app\admin\model\iot\DeviceApk;
use app\admin\model\iot\DeviceApkLog;
use app\admin\validates\DeviceApkValidate;
use app\BaseService;
use job\ThinkQueueJob;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\File;
use think\response\Json;

/**
 * 设备Apk服务层
 */
class DeviceApkService extends BaseService
{

    /**
     * 设备APK列表
     * @param array $params
     * @return Json
     */
    public function deviceApkList(array $params): Json
    {
        $where[] = ['closed', '=', 0];
        //搜索名称
        if ($params['name']) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        //搜索状态
        if (isset($params['status']) and in_array($params['status'], [0, 1])) {
            $where[] = ['status', '=', $params['status']];
        }
        //创建时间筛选
        if ($params['start_time'] && $params['end_time']) {
            $start_time = (int)$params['start_time'];
            $end_time = (int)$params['end_time'];
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        //获取列表
        $data = DeviceApk::getList($where, $params['page'], $params['limit'], 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 设备APK上传
     * @param File $file
     * @return Json
     */
    public function deviceApkUpload(File $file): Json
    {
        $folder = 'apk';
        //数据验证
        validate(['file' => [
            'fileSize' => 100000000,
            'fileExt' => 'apk',
            'fileMime' => 'application/zip',
        ]])->check(['file' => $file]);
        //保存文件
        $savename = Filesystem::putFile('', $file);
        //获取文件完整路径
        $savename = Filesystem::path($savename);
        //获取文件后缀名
        $suffix = pathinfo($savename)['extension'];
        //上传至阿里云
        $AliyunOss = new AliyunOss();
        $res = $AliyunOss->uploadFile($savename, $folder, '.' . $suffix);
        $file_size = @filesize($savename) / 1024;
        //文件授权777
        chmod($savename, 0777);
        unlink($savename);//删除文件
        $data = [
            'src' => $res['src'],
            'src_url' => $AliyunOss->getObjectUrl($res['src']),
            'file_size' => intval($file_size)
        ];
        return jsonReturn(1, $data, '上传成功');
    }

    /**
     * 设备APK添加
     * @param array $params
     * @return Json
     */
    public function deviceApkAdd(array $params): Json
    {
        //数据验证
        try {
            validate(DeviceApkValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //处理参数
        $params['create_time'] = time();
        $params['update_time'] = time();
        //写入数据库
        $id = DeviceApk::insertGetId($params);
        if ($id) {
            return jsonReturn(1, [], '添加成功');
        }
        return jsonReturn(0, [], '添加失败');
    }

    /**
     * 设备APK删除
     * @param int $id
     * @return Json
     */
    public function deviceApkDel(int $id): Json
    {
        //数据验证
        if (!$id) {
            return jsonReturn(0, []);
        }
        //处理参数
        $params['closed'] = 1;
        $params['update_time'] = time();
        //写入数据库
        DeviceApk::update($params, ['id' => $id]);
        return jsonReturn(1, [], '删除成功');
    }

    /**
     * 设备APK上下架
     * @param int $id
     * @param int $status
     * @return Json
     */
    public function deviceApkStatus(int $id, int $status): Json
    {
        //判断参数
        if (!in_array($status, [0, 1])) {
            return jsonReturn(0, [], '参数错误');
        }
        //查询设备APK
        $where = ['id' => $id, 'closed' => 0];
        $Model = DeviceApk::where($where)->find();
        if (!$Model) {
            return jsonReturn(0, [], '设备APK不存在');
        }
        //编辑
        $params['status'] = $status;
        $params['update_time'] = time();
        $res = $Model->save($params);
        if ($res) {
            return jsonReturn(1, []);
        }
        return jsonReturn(0, [], '操作失败');
    }

    /**
     * 设备APK发布
     * @param int $id
     * @param array $mac_ids
     * @return Json
     */
    public function deviceApkRelease(int $id, array $mac_ids): Json
    {
        //验证参数
        if (!$id or !$mac_ids) {
            return jsonReturn(0, [], '参数错误');
        }
        //查找对应的模型
        $field = 'id,version,type,src';
        $where = ['id' => $id, 'status' => 1, 'closed' => 0];
        $apk = DeviceApk::findOne($where, $field);
        if (!$apk) {
            return jsonReturn(0, [], 'APK不存在');
        }
        //补充下载地址
        $apk['src'] = (new AliyunOss())->getObjectUrl($apk['src']);
        //推送至队列
        foreach ($mac_ids as $mac_id) {
            $msg = array_merge($apk, ['mac_id' => $mac_id,]);
            ThinkQueueJob::sendMsg('V2DeviceApkRelease', '', $msg);
        }
        return jsonReturn(1, [], '发布成功');
    }

    /**
     * 设备APK日志列表
     * @param int $id
     * @param int $page
     * @param int $limit
     * @return Json
     */
    public function deviceApkLogList(int $id, int $page, int $limit): Json
    {
        //验证参数
        if (!$id) {
            return jsonReturn(0, [], '参数错误');
        }
        //查找数据
        $where[] = ['apk_id', '=', $id];
        $data = DeviceApkLog::getList($where, $page, $limit, 'id desc');
        return jsonReturn(1, $data);
    }


}
